package com.wink_172.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.wink_172.commons.R;

/**
 * 原版代码
 * **/
public class MySurfaceViewM extends SurfaceView implements SurfaceHolder.Callback{

	SurfaceHolder mSurfaceHolder;
	boolean isRun;
	Bitmap bitmap;/** 进度条背景**/
	float angle = 0;	/** 移动角度**/
	float width;/** 包围进度条背景的圆半径**/
	float speed;/** 移动速度**/

	public MySurfaceViewM(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		mSurfaceHolder = this.getHolder();
		mSurfaceHolder.addCallback(this);
		/** 加载进度条**/
		bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_collect01).copy(Bitmap.Config.ARGB_8888, true);
		/** 计算半径**/
		width = (float) Math.sqrt(Math.pow(bitmap.getWidth()/2, 2) + Math.pow(bitmap.getHeight()/2, 2));
		/** 根据25s，计算移动速度**/
		speed = (float) (360 / (25000 / 33.0));
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {


	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		isRun = true;
		new Thread(){
			public void run(){
				while(isRun){
					long start = System.currentTimeMillis();
					Canvas canvas = null;
					synchronized (mSurfaceHolder) {
						canvas = mSurfaceHolder.lockCanvas();
						if(canvas != null ){
							onGameDraw(canvas);
							if(canvas != null && mSurfaceHolder != null){
								mSurfaceHolder.unlockCanvasAndPost(canvas);
							}
							angle += speed;
							if(angle >= 360)
								angle = 0;
						}
					}
					long end = System.currentTimeMillis() - start;
					if(end < 33){
						try {
							Thread.sleep(end);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		isRun = false;
	}

	private void onGameDraw(Canvas canvas){

	     canvas.drawColor(Color.BLACK);
	     Paint paint = new Paint();
	     paint.setFilterBitmap(false);
		canvas.save();

		// 绘制进度条背景
	     canvas.drawBitmap(bitmap, 0, 0, paint);
		// 设置遮挡属性
	     paint.setXfermode(new PorterDuffXfermode(Mode.DST_OUT));

		// 绘制遮挡扇形
	     canvas.drawArc(new RectF(-(width - bitmap.getWidth()/2), -(width - bitmap.getHeight()/2), width *2, width *2), 0, angle, true, paint);

	}
}
